import uuid

from django.shortcuts import render, HttpResponse
from api import models
from rest_framework.views import APIView
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework import exceptions
from ext.auth import BlogAuthentication,NoAuthentication
from ext.hook import NbHookSerializer


# Create your views here.
def db(request):
    # v1 = models.UserInfo.objects.create(username="wuzhubo", password="123")
    # v2 = models.UserInfo.objects.create(username="yanting", password="520")
    #
    # models.Blog.objects.create(
    #     category=1,
    #     image="xxxx/xxxx.png",
    #     title="震惊了",
    #     summary="....",
    #     text="撒大达娃萨达撒迪扫地hi的时候i十四阿达",
    #     creator=v1,
    # )
    #
    # models.Blog.objects.create(
    #     category=2,
    #     image="xxxx/xxxx.png",
    #     title="震惊了我的天",
    #     summary="....",
    #     text="塌方了啊啊啊啊啊啊啊",
    #     creator=v2,
    # )
    models.Comment.objects.create(content="xxxxx1", blog_id=1, user_id=1)
    models.Comment.objects.create(content="xxxxx1fffffffffffff", blog_id=1, user_id=2)

    return HttpResponse("成功")


class BlogUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = ["id", "username"]


class BlogSerializer(NbHookSerializer,serializers.ModelSerializer):
    ctime = serializers.DateTimeField(format="%Y-%m-%d",read_only=True)
    creator = BlogUserSerializer(read_only=True)

    class Meta:
        model = models.Blog
        fields = ["category", "image", "title", "text", "summary", "ctime",
                  "comment_count", "favor_count", "creator"]
        extra_kwargs = {
            "comment_count": {"read_only": True},
            "favor_count": {"read_only": True},
            "text":{"write_only": True}
        }

    def nb_category(self,obj):
        return obj.get_category_display()


class BlogView(APIView):
    authentication_classes = [BlogAuthentication,]

    def get(self, request, *args, **kwargs):
        """博客列表"""

        # 读取博客信息
        queryset = models.Blog.objects.all().order_by("-id")

        # 序列化
        ser = BlogSerializer(instance=queryset, many=True)

        context = {"code": 1000, "data": ser.data}

        return Response(context)

    def post(self,request):
        if not request.user:
            return Response({"code":3000,"error":"认证失败"})
        ser = BlogSerializer(data=request.data)
        if not ser.is_valid():
            return Response({"code": 1002, "error": "校验失败","detail": ser.errors})

        ser.save(creator=request.user)
        return Response({"code":1000,"data":ser.data})



class BlogDetailSerializer(serializers.ModelSerializer):
    category = serializers.CharField(source="get_category_display")
    ctime = serializers.DateTimeField(format="%Y-%m-%d")
    creator = BlogUserSerializer()
    comments = serializers.SerializerMethodField()

    class Meta:
        model = models.Blog
        fields = "__all__"


class BlogDetailView(APIView):
    def get(self, request, *args, **kwargs):
        """博客列表"""
        # 获取id
        pk = kwargs.get("pk")

        # 读取博客信息
        instance = models.Blog.objects.filter(id=pk).first()
        if not instance:
            return Response({"code": 1001, "error": "数据不存在"})

        # 序列化
        ser = BlogDetailSerializer(instance=instance, many=False)

        context = {"code": 1000, "data": ser.data}

        return Response(context)


from ext.hook import NbHookSerializer


class CommentSerializers(NbHookSerializer, serializers.ModelSerializer):
    class Meta:
        model = models.Comment
        fields = ["id", "content", "user"]
        extra_kwargs = {
            "id":{"read_only": True},
            "user":{"read_only":True}
        }

    def nb_user(self, obj):
        return obj.user.username


class BlogCommentView(APIView):
    authentication_classes = [BlogAuthentication, ]
    def get(self, request, blog_id):
        """评论列表"""
        queryset = models.Comment.objects.filter(blog_id=blog_id)

        # 序列化
        ser = CommentSerializers(instance=queryset, many=True)

        context = {"code": 1000, "data": ser.data}

        return Response(context)

    def post(self, request, blog_id):
        """发表评论"""

        if not request.user:
            return Response({"code": 3000, "error": "认证失败"})

        blog_object = models.Blog.objects.filter(id=blog_id).first()
        if not blog_object:
            return Response({"code": 2000, "error": "博客不存在"})

        ser = CommentSerializers(data=request.data)
        if not ser.is_valid():
            return Response({"code":10002,"error":"博客不存在","detail":ser.errors})

        ser.save(blog=blog_object,user=request.user)
        return Response({"code": 1000, "data": ser.data})


class RegisterSerializers(serializers.ModelSerializer):
    confirm_password = serializers.CharField(write_only=True)

    class Meta:
        model = models.UserInfo
        fields = ["id","username", "password", "confirm_password"]
        extra_kwargs = {
            "id":{"read_only":True},
            "password": {"write_only":True}}

    def validate_password(self,value):
        # print("密码",value)
        return value

    def validate_confirm_password(self, value):
        # print("重复密码",value)
        password = self.initial_data.get("password")
        if password != value:
            raise exceptions.ValidationError("密码不一致")
        return value


class RegisterView(APIView):
    def post(self, request):

        # 提交数据

        # 校验
        ser = RegisterSerializers(data=request.data)
        if ser.is_valid():
            ser.validated_data.pop("confirm_password")
            ser.save()
            # ser.save()
            # print(self.validated_data)
            return Response({"code": 1000, 'data': "xxx"})
        else:
            return Response({"code": 1001, 'error': '注册失败', 'detail': ser.errors})


class LoginSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = ["username","password"]

class LoginView(APIView):

    def post(self, request):
        ser = LoginSerializers(data=request.data)
        if not ser.is_valid():
            return Response({"code":1003,"error":"校验失败","detail":ser.errors})
        instance = models.UserInfo.objects.filter(**ser.validated_data).first()
        if not instance:
            return Response({"code":1002,"error":"用户名或密码错误"})

        token = str(uuid.uuid4())
        instance.token = token
        instance.save()

        return Response({"code":1000,"token":token})

class FavorSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.Favor
        fields = ["blog"]

class FavorView(APIView):
    authentication_classes = [BlogAuthentication,NoAuthentication]
    def post(self,request):
        print(request.user)
        ser = FavorSerializers(data=request.data)
        if not ser.is_valid():
            return Response({"code":1002,"error":"加载失败","detail":ser.errors})

        # 存在，不赞
        exists = models.Favor.objects.filter(user=request.user,blog=ser.validated_data["blog"]).exists()
        if exists:
            return Response({"code": 1005, "error": "已存在"})
        # 不存在，赞
        ser.save(user=request.user)
        return Response({"code":1000,"data":ser.data})

